package com.liuda066.forumssm.exception;

import com.liuda066.forumssm.common.AppResult;
import com.liuda066.forumssm.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/9/1 10:48
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    //处理⾃定义的已知异常
    public AppResult handleApplicationException(ApplicationException e){
        e.printStackTrace();

        log.error(e.getMessage());

        if (e.getErrorResult() != null){
            return e.getErrorResult();
        }
        return AppResult.failed(e.getMessage());
    }

    //处理全未捕获的其他异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handleException (Exception e) {
        // 打印异常
        e.printStackTrace();
        // 记录⽇志
        log.error(e.getMessage());
        if (e.getMessage() == null) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        // 默认返回异常信息
        return AppResult.failed(e.getMessage());
    }
}
